package com.exthirteen.textgamescript.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.exthirteen.textgamescript.model.vo.ResultStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;

public class BaseEnumDeserializer extends JsonDeserializer<IEnum<?>> {

    @Override
    public IEnum<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        JsonNode node = jp.getCodec().readTree(jp);
        String currentName = jp.currentName();
        Object currentValue = jp.getCurrentValue();
        Class findPropertyType = null;
        if(currentValue instanceof Collection) {

            JsonStreamContext parsingContext = jp.getParsingContext();

            JsonStreamContext parent = parsingContext.getParent();
            Object currentValue3 = parent.getCurrentValue();
            String currentName3 = parent.getCurrentName();
            try {
                Field listField = currentValue3.getClass().getDeclaredField(currentName3);
                ParameterizedType listGenericType = (ParameterizedType) listField.getGenericType();
                Type listActualTypeArguments = listGenericType.getActualTypeArguments()[0];
                findPropertyType = (Class) listActualTypeArguments;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        }
        if(findPropertyType == null) {
            throw BaseException.get(ResultStatus.COM_ERROR.getCode(), "数据格式异常");
        }
        Serializable asText = null;
        if(node.getNodeType() == JsonNodeType.STRING) {
            asText = node.asText();
        }else if (node.getNodeType() == JsonNodeType.NUMBER){
            asText = node.asInt();
        }
        IEnum valueOf = null;
        if(StringUtils.isNotBlank(String.valueOf(asText))){
            valueOf = (IEnum<?>) IEnum.idOf(asText, findPropertyType);
        }
        return valueOf;
    }
}
